<?php
/**
 * 菜单管理类
 * @author 肖小平
 *
 */
class MenuAction extends BaseAction{
	//展示菜单列表
    public function menu_list(){
    	$menus = M('AdminMenu')->select();//查找数据库 返回array
    	$menu_arr_list = array();
    	//获取第一级菜单
    	foreach ($menus as $m) {
    		if ($m['p_id']==0){
    			$menu_arr_list[] = $m;
    		}
    	}
    	//获取二级菜单
    	foreach ($menu_arr_list as $k=>$m_arr){
    		foreach ($menus as $m) {
    			if ($m['p_id']==$m_arr['id']){
    				$menu_arr_list[$k]['sub_menu'][] = $m;
    			}
    		}
    	}
    	$this->assign('menu_arr_list',$menu_arr_list);//向模板输出变量
		$this->display();//输出模板
    }
    //添加一级菜单
    public function menu_add(){
    	if($_POST){
	    	$_POST['sort'] = $_POST['sort']?$_POST['sort']:0;//排序
	    	$_POST['p_id'] = 0;
	    	M('AdminMenu')->add($_POST);
	    	$this->success('添加一级菜单成功',U('Menu/menu_list'));
	    	exit;
    	}
    	$this->display();
    }
    //添加二级菜单
    public function sub_menu_add(){
    	if($_POST){
	    	$_POST['sort'] = $_POST['sort']?$_POST['sort']:0;
	    	M('AdminMenu')->add($_POST);
	    	$this->success('添加二级菜单成功',U('Menu/menu_list'));
	    	exit;
    	}
    	$this->display();
    }
    //修改菜单
    public function menu_edit(){
    	if($_POST){
    		M('AdminMenu')->data($_POST)->save();
    		$this->success('修改成功',U('Menu/menu_list'));
    		exit;
    	}
    	$id = $_GET['id'];
    	$menu = M('AdminMenu')->where("id=$id")->find();
    	$menus = M('AdminMenu')->select();
    	$menu_arr = array();
    	foreach ($menus as $m) {
    		if ($m['parent_id']==0){
    			$menu_arr[] = $m;
    		}
    	}
    	foreach ($menu_arr as $k=>$m_arr){
    		foreach ($menus as $m) {
    			if ($m['parent_id']==$m_arr['id']){
    				$menu_arr[$k]['sub_menu'][] = $m;
    			}
    		}
    	}
    	$this->assign('menu_1',$menu_arr);
    	$this->assign('menu',$menu);
    	$this->display();
    }
    public function menu_delete(){
    	$id = $_GET['id'];
    	M('AdminMenu')->where("id=$id")->delete();
    	M('AdminMenu')->where("p_id=$id")->delete();
    	$this->success('删除成功',U('Menu/menu_list'));
    }
}